<template>
  <div class="circuit-board">
    <div class="close-btn" @click="toggleLock">
      <img v-if="isLocked" :src="lockImg" class="icon" />
      <img v-else :src="unlockImg" class="icon" />
    </div>
    <canvas
      id="board"
      canvas-id="board"
      class="board-canvas"
      @touchstart="onTouchStart"
      @touchmove="onTouchMove"
      @touchend="onTouchEnd"
    ></canvas>
    <canvas
      id="magnifier"
      canvas-id="magnifier"
      class="magnifier-canvas"
      :class="{ hide: !showMagnifier }"
    ></canvas>
    <ActionBar
      :padding-bottom="paddingBottom"
      :is-redo="canRedo"
      :is-undo="canUndo"
      :scale="scale"
      @preview="onPreview"
      @redo="onRedo"
      @reset="onReset"
      @scale="onScale"
      @undo="onUndo"
    />
  </div>
</template>

<script>
import ActionBar from './components/ActionBar.vue';
import * as assets from './assets.js';
import { App } from './circuitApp.js';
import * as questionData from './questionData.js';

export default {
  name: 'CircuitBoard',
  components: { ActionBar },
  data() {
    return {
      isLocked: false,
      showBoard: true,
      showMagnifier: false,
      showActionBar: true,
      canRedo: false,
      canUndo: false,
      scale: 0,
      paddingBottom: 0,
      lockImg: assets.bLock,
      unlockImg: assets.bUnlock,
      board: null,
      magnifier: null,
      app: null,
      currentData: null,
    };
  },
  onLoad(options) {
      // this.currentData = {
      //   id: 22,
      //   name: "K2-1电动机单向连续带点动运转接线",
      //   preview: "https://dpsystem.oss-cn-shenzhen.aliyuncs.com/moren1607659060/5b59eb42d04801fc13ae4b69302d5d70",
      //   sort: 0,
      //   type: 1,
      // }
      console.log(options, 'options');
      // 题库映射
      const typeMap = {
        1: questionData.familyCircuits,
        2: questionData.industryCircuits,
        3: questionData.practical,
      };
      // 获取题目数据
      // this.currentData = typeMap[options.type][options.id];
      
      this.currentData = typeMap[3][22];
      console.log(this.currentData, 'this.currentData');
      
      uni.setNavigationBarTitle({
        title: this.currentData.name
      });
  },
  onReady() {
    setTimeout(() => {
    this.initApp();
  }, 100);
  },
  methods: {
    initApp() {
      // 小程序端canvas 2.0写法
      uni.createSelectorQuery()
        .in(this)
        .select('#board')
        .fields({ node: true, size: true })
        .exec(res => {
          const canvas = res[0].node;
          const ctx = canvas.getContext('2d', { willReadFrequently: true });
          const dpr = uni.getSystemInfoSync().pixelRatio;
          canvas.width = res[0].width * dpr;
          canvas.height = res[0].height * dpr;
          ctx.scale(dpr, dpr)
          canvas.createImage = canvas.createImage || function () { return new Image() }
          console.log(canvas, 'canvas');
          
          this.app = new App({
            canvas,
            ctx,
            dpr,
            baseScale: 1,
          })
          
            // 绑定渲染回调
            this.app.onRender(() => {
            this.canUndo = this.app.lines.length > 0
            this.canRedo = this.app.undoLines.length > 0
            this.scale = this.app.isScaleChange ? Math.round(this.app.viewScale * 100) : 0
            this.showMagnifier = this.app.showMagnifier
          })
          console.log('app', this.app, this.currentData);
          
           // 加载元件
           this.currentData.data.forEach(comp => {
            this.app.addComponent(comp)
          })
            // 非PC端放大镜
          const sysInfo = uni.getSystemInfoSync()
          if (!['windows', 'mac'].includes(sysInfo.platform)) {
            uni.createSelectorQuery()
              .in(this)
              .select('#magnifier')
              .fields({ node: true, size: true })
              .exec(res => {
                const magCanvas = res[0].node
                const magCtx = magCanvas.getContext('2d')
                const magDpr = uni.getSystemInfoSync().pixelRatio
                magCanvas.width = res[0].width * magDpr
                magCanvas.height = res[0].height * magDpr
                magCtx.scale(magDpr, magDpr)
                this.app.setMagnifier({ canvas: magCanvas, ctx: magCtx })
              })
          }
        });
    },
    toggleLock() {
      this.isLocked = !this.isLocked;
      if (this.app) this.app.lockCanvas();
    },
    onTouchStart(e) {
      if (this.app) this.app.onTouchStart(e);
    },
    onTouchMove(e) {
      if (this.app) this.app.onTouchMove(e);
    },
    onTouchEnd(e) {
      if (this.app) this.app.onTouchEnd(e);
    },
    onPreview(type) {
      // 预览图片逻辑
      const url = type === 1 ? this.currentData.principleImage : this.currentData.sampleImage;
      // uni.previewImage({ urls: [url] });
      window.open(url, '_blank');
    },
    onRedo() {
      if (this.app) this.app.redo();
    },
    onUndo() {
      if (this.app) this.app.undo();
    },
    onReset() {
      if (this.app) this.app.reset();
    },
    onScale() {
      if (this.app) this.app.zoomIn();
    },
  },
};
</script>

<style scoped>
.circuit-board {
  position: relative;
  width: 100vw;
  height: 100vh;
  background: #fff;
}
.close-btn {
  position: absolute;
  right: 4px;
  top: 4px;
  z-index: 10;
  padding: 8px;
}
.icon {
  width: 25px;
  height: 25px;
}
.board-canvas {
  width: 100vw;
  height: 100vh;
  display: block;
}
.magnifier-canvas {
  width: 60px;
  height: 60px;
  position: absolute;
  right: 0;
  top: 0;
  z-index: 20;
  box-shadow: 0 2px 8px #eee;
  background: #f8f9fa;
  border-bottom-left-radius: 8px;
}
.hide {
  right: -100% !important;
}
</style>
